var layedit;
var layeditId;
var fileSrc=new Array();
var lodding;
var currentBox=0;
$(function() {
	
	$("[name='remail']").focus(function(){
		currentBox=1;
	});
	$("[name='copyto']").focus(function(){
		currentBox=2;
	});
	$("[name='bcopyto']").focus(function(){
		currentBox=3;
	});
	layui.use('layedit', function() {
		layedit = layui.layedit;
		layedit.set({
			  uploadImage: {
			    url: '/mail/uploadImg'
			  }
			});
		layeditId=layedit.build('demo'); // 建立编辑器
	});
	layui.use('table', function() {
		table = layui.table;
		 // 监听单元格事件
		  table.on('tool(tableFilter)', function(obj){
		    if(obj.event === 'addContact'){
		    	var data = obj.data;
		    	if(currentBox==1||currentBox==0){
		    		var remail=$("[name='remail']").val();
		    		if(remail.indexOf(data.email)==-1){
		    			$("[name='remail']").val(remail+data.name+"<"+data.email+">,");
		    		}
		    	}else if(currentBox==2){
		    		var copyto=$("[name='copyto']").val();
		    		if(copyto.indexOf(data.email)==-1){
		    			$("[name='copyto']").val(copyto+data.name+"<"+data.email+">,");
		    		}
		    	}else if(currentBox==3){
		    		var bcopyto=$("[name='bcopyto']").val();
		    		if(bcopyto.indexOf(data.email)==-1){
		    			$("[name='bcopyto']").val(bcopyto+data.name+"<"+data.email+">,");
		    		}
		    	}
		    }
		  });		  
	});
	layui.use('upload', function(){
		  var $ = layui.jquery
		  var upload = layui.upload;
		  layeditUpload=upload;
		  var demoListView = $('#demoList');
		  var uploadListIns = upload.render({
			elem: '#testList'
			,url: '/mail/uploadFile'
	    	,accept: 'file'
		    ,multiple: true
		    ,auto: false
		    ,bindAction: '#testListAction'
		    ,choose: function(obj){   
		      var files = this.files = obj.pushFile(); // 将每次选择的文件追加到文件队列
		      // 读取本地文件
		      obj.preview(function(index, file, result){
		        var tr = $(['<tr id="upload-'+ index +'">'
		          ,'<td>'+ file.name +'</td>'
		          ,'<td>'+ (file.size/1014).toFixed(1) +'kb</td>'
		          ,'<td>等待上传</td>'
		          ,'<td>'
		            ,'<button class="layui-btn layui-btn-mini demo-reload layui-hide">重传</button>'
		            ,'<button class="layui-btn layui-btn-mini layui-btn-danger demo-delete">删除</button>'
		          ,'</td>'
		        ,'</tr>'].join(''));
		        
		        // 单个重传
		        tr.find('.demo-reload').on('click', function(){
		          obj.upload(index, file);
		        });
		        
		        // 删除
		        tr.find('.demo-delete').on('click', function(){
		          delete files[index]; // 删除对应的文件
		          tr.remove();
		          uploadListIns.config.elem.next()[0].value = '';
		        });
		        demoListView.append(tr);
	      });
	    }
	    ,done: function(res, index, upload){
	    	console.log(res);
	    	console.log(index);
	    	console.log(upload);
	      if(res.code == 0){ // 上传成功
	    	fileSrc.push(res.data.src);
	        var tr = demoListView.find('tr#upload-'+ index);
	        var tds = tr.children();
	        tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
	        tds.eq(3).html(''); // 清空操作
	        return delete this.files[index]; // 删除文件队列已经上传成功的文件
	      }
	      this.error(index, upload);
	    }
	    ,error: function(index, upload){
	      var tr = demoListView.find('tr#upload-'+ index)
	      ,tds = tr.children();
	      tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
	      tds.eq(3).find('.demo-reload').removeClass('layui-hide'); // 显示重传
	    }
	  });
	});
	layui.use(['form', 'layedit', 'laydate'], function(){
		  var form = layui.form;
		  var layer = layui.layer;
		  // 监听提交
		  form.on('submit(demo1)', function(data){
			  lodding=layer.load(1);
				$.ajax({
					type : "POST",
					url : "/mail/sendEmail",
					data:{
						"sendmail":$("[name='sendmail']").val(),
						"remail":$("[name='remail']").val(),
						"copyto":$("[name='copyto']").val(),
						"bcopyto":$("[name='bcopyto']").val(),
						"subject":$("[name='subject']").val(),
						"priority":$("[name='priority']").is(":checked"),
						"notification":$("[name='notification']").is(":checked"),
						"bodytext":layedit.getContent(layeditId),
						"file":fileSrc
					},
					async : true,
					success : function(msg) {
						layer.close(lodding);
						msg=JSON.parse(msg);
					    layer.alert(msg['msg'], {
					      title: '消息'
					    });
					},
					error : function() {
						layer.close(lodding);
					}
				});
		    return false;
		  });
		  form.on('submit(demo2)', function(data){
			 lodding=layer.load(1); 
			 $.ajax({
					type : "POST",
					url : "/mail/saveDrafts",
					data:{
						"sendmail":$("[name='sendmail']").val(),
						"remail":$("[name='remail']").val(),
						"copyto":$("[name='copyto']").val(),
						"bcopyto":$("[name='bcopyto']").val(),
						"subject":$("[name='subject']").val(),
						"priority":$("[name='priority']").is(":checked"),
						"notification":$("[name='notification']").is(":checked"),
						"bodytext":layedit.getContent(layeditId),
						"file":fileSrc
					},
					async : true,
					success : function(msg) {
						layer.close(lodding);
						msg=JSON.parse(msg);
					    layer.alert(msg['msg'], {
					      title: '消息'
					    });
					},
					error : function() {
						layer.close(lodding);
					}
				});
			  return false;
		  });
	});
});